package com.liu.network.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Client2 {
	// 十六进制转byte数组
	public static byte[] hexStringToByteArray(String hexStr) {
	    if(hexStr.length()%2 == 1){
	       hexStr = "0"+hexStr;
	    }
	    int len = hexStr.length()/2;
	    byte[] result = new byte[len];
	    char[] chars = hexStr.toCharArray();
	    for(int i=0;i<len;i++){
	        result[i] = (byte)(charToByte(chars[i])<<4 | charToByte(chars[i+1]));
	    }
	    return result;
	}

	private static int charToByte(char c) {
		String chars = "0123456789ABCDEF";
	    byte b = (byte)chars.indexOf(c);
	    return b;
	}
	/** 
	 * 字节数组转16进制 
	 * @param bytes 需要转换的byte数组 
	 * @return  转换后的Hex字符串 
	 */  
	public String bytesToHexString(byte[] bArr) {
	    StringBuffer sb = new StringBuffer(bArr.length);
	    String sTmp;

	    for (int i = 0; i < bArr.length; i++) {
	        sTmp = Integer.toHexString(0xFF & bArr[i]);
	        if (sTmp.length() < 2)
	            sb.append(0);
	        sb.append(sTmp.toUpperCase());
	    }
	    return sb.toString();
	}
	
	public static void main(String[] args) {
		try {
			Socket socket = new Socket("192.168.3.11", 6789);
			//往服务器发送请求
			OutputStream os = socket.getOutputStream();
			byte[] head = new byte[8];
			byte[] requestFlag = hexStringToByteArray("464E4950");
			byte[] requestDateLen = new byte[4];
			requestDateLen = "0".getBytes();
			for (int i = 0; i < requestFlag.length; i++) {
				head[i] = requestFlag[i];
			}
			for (int i = 0; i < requestDateLen.length; i++) {
				head[i + 4] = requestDateLen[i];
			}
			os.write(head);
			os.flush(); 
			socket.shutdownOutput(); 
			
			//接收服务器的响应
			InputStream is = socket.getInputStream();
			byte[] responseFlag = new byte[4];
			byte[] responseDateLen = new byte[4];
			byte[] responseDate = new byte[4];
			int r = -1;
			List<Byte> list = new LinkedList<Byte>();
			while ((r = is.read(responseFlag)) != -1) {
				list.add(Byte.valueOf((byte) r));
			}
			byte[] data = new byte[list.size()];
			for (int i = 0; i < list.size(); i++) {
				data[i] = list.get(i);
			}
			String str = new String(data);
			System.out.println("服务器返回参数"+str);
			
			// 关闭资源 
			is.close(); 
			os.close(); 
			socket.close(); 
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
}